﻿var scratchPadGrid = scratchPadGrid || {};

scratchPadGrid = function () {
    var gridInEditMode = false;
    var scratchDropDownChanged = false;
    var scratchDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetScratchHistory",
                type: "get",
                dataType: "json",
                cache: false
            },
            create: {
                url: "/ScratchPad/CreateScratchHistory",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            update: {
                url: "/ScratchPad/UpdateScratchHistory",
                type: 'POST',
                dataType: "json",
                contentType: "application/JSON"
            },
            destroy: {
                url: "/ScratchPad/DeleteScratchHistory",
                type: "POST",
                dataType: "json",
                contentType: "application/JSON"
            },
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }
        },
        pageSize: 10,
        schema: {
            model: {
                id: "clid",
                fields: {
                    clid: {
                        editable: false, nullable: true,
                        type: "int"
                    },
                    caller: {
                        type: "string",
                        validation: { required: true }
                    },
                    phone: {

                        type: "string"
                    },
                    loggedOwner:
                         {
                             defaultValue: $("#hdnusername").val(),
                             type: "string"

                         },


                    Name: {
                        type: "string"
                    },
                    companyid: {
                        editable: true,
                        type: "int"
                    },
                    company: {
                        type: "string"
                    },
                    ContactId: {
                        type: "int"

                    },
                    productid: {
                        editable: true,
                        type: "int"
                    },
                    notes: {
                        type: "string"


                    },
                    product: {
                        type: "string"

                    },
                    viaId: {
                        type: "int"

                    },
                    commVia:
                        {
                            type: "string",

                        },
                    inOrOut: {
                        type: "string",
                        defaultValue: "In",
                    },
                    status: {
                        type: "int"
                    },
                    statusName: {
                        type: "string",
                        defaultValue: "Open",
                    },
                    contactname: {
                        type: "string"
                    },

                    visibleToOthers: {
                        type: "boolean",
                        defaultValue: false,
                        filterable: {
                            messages: {
                                isTrue: "Active", // sets the text for "isTrue" radio button
                                isFalse: "Inactive",
                            }
                        }
                    },
                    updateDate:
                    {
                        type: "date"

                    },


                    error: function (a) {
                        $('#scratchGrid').data("kendoGrid").cancelChanges();
                    },

                }
            }
        }
    });


    var company = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetJustCompanyName/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });

    var products = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetAllProducts/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }

        },
        requestEnd: function (a, b) {

        }
    });
    var contactedVia = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetAllCommunicationMedium/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        },
        requestEnd: function (a, b) {

        }
    });
    var status = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetStatus/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });


    var contactDetails = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetContactDetail/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        },
        requestEnd: function (a, b) {

        }

    });
    var callerDetails = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetCallerDetail/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var phoneDetails = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/ScratchPad/GetPhoneNumbers/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var involuedEmployees = new kendo.data.DataSource({
        transport: {
            read: function (options) {
                $.ajax({
                    type: "GET",

                    url: "../EmployeeGrid/GetEmployees",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (data) {
                        options.success(data);
                    }
                });
            }
        }
    });

    return {
        scratchDataSource: scratchDataSource,
        company: company,
        products: products,
        contactedVia: contactedVia,
        status: status,
        callerDetails: callerDetails,
        contactDetails: contactDetails,
        phoneDetails: phoneDetails,
        gridInEditMode: gridInEditMode,
        involuedEmployees: involuedEmployees,
        scratchDropDownChanged: scratchDropDownChanged
    }
}();

$(function () {

    $(window).on("beforeunload", function () {
        if (scratchPadGrid.gridInEditMode) {
            return "Are you sure you want to discard all your changes."
        }
    });


    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }


    $("#scratchGrid").kendoGrid({
        dataSource: scratchPadGrid.scratchDataSource,
        scrollable: true,
        height: "250px",
        toolbar: [{ name: "create", text: "New Call Log" }, "excel"], //, "save", "cancel"],
        excel: {
            allPages: true,
            fileName: "NewCallLogExport.xlsx"
        },
        pageable: true,
        height: 500,
        columns: [
     { field: "loggedOwner", title: "Created User", filterable: true, width: "10em", editable: true },
      { field: "caller", title: "Caller *", filterable: true, editor: callerAutoCompleteEditor, width: "8em" },
      { field: "phone", title: "Phone", editor: phoneAutoCompleteEditor, width: "8em" },
      { field: "Name", title: "Contact", width: "8em", editor: contactAutoCompleteEditor },
      { field: "company", title: "Company", editor: companyDropDownEditor, width: "8em" },
      { field: "product", title: "Products", editor: productDropDownEditor, sortable: true, width: "8em" },
       { field: "contactname", title: "Employees ", editor: invlouedEmployeeDropDownEditor, width: "10em" },

      { field: "commVia", title: "Contacted via", editor: contactedviaDropDownEditor, width: "8em" },
      { field: "inOrOut", title: "Incoming Or Outgoing ", editor: incomingOrOutgoingDropDownEditor, width: "8em" },
      { field: "statusName", title: "Status", editor: statusDropDownEditor, width: "8em" },
        {
            field: "notes",
            title: "Notes",
            width: "200px",
            attributes: {
                style: 'white-space: nowrap '
            },
            //template: kendo.template($("#storeTerritory").html()),
            sortable: true,


            editor: function (container, options) {
                $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
            }
        },
    {
        field: "updateDate", title: "UpdateDate*", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
        editor: dateTimeEditor, width: "8em",
        filterable: {
            ui: "datetimepicker"
        }
    },

      {
          field: "visibleToOthers", title: "VisibleToOthers*", template: '<input type="checkbox" #=visibleToOthers ? \'checked="checked"\' : "" # class="chkbx" onclick="return false;" />',
          filterable: {
              messages: {
                  isTrue: "Active", // sets the text for "isTrue" radio button
                  isFalse: "Inactive",
              }
          },
          width: "8em"
      },

      {
          title: "&nbsp;",
          width: "12em",
          //command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {

                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      ////see what is coming in dataItem
                      //if (dataItem.QuestionAnswers.length > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                      deleteTopicConfirmation(e, this);
                      // }
                      return false;
                  }
              }
          ]
      }
        ],

        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                    contains: "Contains"
                }
            }
        },

        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },

        cancel: function () {
            scratchPadGrid.gridInEditMode = false;
        },


        excelExport: function (e) {
            for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                e.workbook.sheets[0].columns[i].autoWidth = true;
            }
        },


    });




    $("#scratchGrid").kendoTooltip({
        filter: "td:nth-child(10)", //this filter selects the second column's cells
        position: "left",
        content: function (e) {
            var target = e.target;
            return $(target).text();

        }
    }).data("kendoTooltip");





    scratchPadGrid.scratchDataSource.bind("requestEnd", showSuccessMessage);




    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            scratchPadGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();
        }
    }


    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });


    function deleteTopicConfirmation(e, widget) {
        var grid = $('#scratchGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

    function companyDropDownEditor(container, options) {
        console.log(options);
        $('<input id="CompanyValue" data-text-field="cpName" data-value-field="cpName" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "cpName",
            dataTextField: "cpName",
            dataSource: scratchPadGrid.company,

        });
    }
    function productDropDownEditor(container, options) {

        $('<input id="ProductValue" data-text-field="product" data-value-field="product"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "product",
            dataTextField: "product",
            dataSource: scratchPadGrid.products
        });
    }
    function statusDropDownEditor(container, options) {

        $('<input id="StatusValue" data-text-field="statusName" data-value-field="statusName"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "statusName",
            dataTextField: "statusName",
            dataSource: scratchPadGrid.status

        });
    }
    function contactedviaDropDownEditor(container, options) {

        $('<input id="ContactedViaValue" data-text-field="commVia" data-value-field="commVia"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataValueField: "commVia",
            dataTextField: "commVia",
            dataSource:
                scratchPadGrid.contactedVia

        });
    }

    function incomingOrOutgoingDropDownEditor(container, options) {
        $('<input id="InOrOutValue" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,
            dataSource: { data: [{ dataText: "In", dataValue: "1", selected: true }, { dataText: "Out", dataValue: "2" }] }

        });
    }

    function callerAutoCompleteEditor(container, options) {
        $('<input required="required" name="code"  data-text-field="callercompany"  data-value-field="caller"  data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoAutoComplete({
                dataValueField: "callercompany",
                dataTextField: "callercompany",
                suggest: true,
                placeHolder: "Enter Caller Name here",
                filter: "contains",
                index: 1,
                minLength: 1,
                dataSource: scratchPadGrid.callerDetails
            });

        $('<span class="k-invalid-msg" data-for="code"></span>').appendTo(container);
    }
    function phoneAutoCompleteEditor(container, options) {
        $('<input data-text-field="phone"  data-value-field="phone"  data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoAutoComplete({
                dataValueField: "phone",
                dataTextField: "phone",
                suggest: true,
                placeHolder: "Enter Phone Number",
                filter: "contains",
                index: 1,
                minLength: 1,
                dataSource: scratchPadGrid.phoneDetails
            });
    }
    function invlouedEmployeeDropDownEditor(container, options) {
        $('<input id="StatusValue" data-text-field="contactname" data-value-field="contactname"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
            autoBind: false,

            dataSource: scratchPadGrid.involuedEmployees

        });
    }
    function contactAutoCompleteEditor(container, options) {
        $('<input data-text-field="name"  data-value-field="ContactId"  data-bind="value:' + options.field + '"/>')
        .appendTo(container)
        .kendoAutoComplete({
            //dataValueField: "ContactId",
            //dataTextField: "name",
            suggest: true,
            placeHolder: "Enter Contact Name",
            filter: "contains",
            //   index: 1,
            minLength: 1,
            dataSource: scratchPadGrid.contactDetails
        });
    }

});
function getCompany(company) {
    return company;
}